//
// Created by SDSC\202100300261 on 23-11-17.
//

#include "Memory.h"
#include <stdexcept>
Memory::Memory() {
    this->P = 0;
    this->T = 0;
    this->B = 0;
}
Memory::Memory(std::vector<CodeEntry>*_code) {
    this->P = 0;
    this->T = -1;
    this->B = 0;
    this->codes = _code;
}

CodeEntry *Memory::getCode() {
    return &codes -> at(P++);
}
void Memory::push(int value) {
    S.push_back(value);
    ++T;
}
int Memory::pop() {
    int ret = S[T--];
    S.pop_back();
    return ret;
}
int Memory::getTop() {
    return S[T];
}
void Memory::set(int index, int value) {
    if(index < 0 || index > T) {
        throw std::runtime_error("index out of range");
    }
    S[index] = value;
}
/**
 * 获取与当前相差level层的基地址
 */
int Memory::getLevelAdr(int level) {
    int ret = B;
    while(level > 0) {
        ret = S[ret];
        level--;
    }
    return ret;
}
